package com.zhu.salesmanagement.network;

import org.apache.http.conn.HttpHostConnectException;
import org.xmlrpc.android.XMLRPCClient;
import org.xmlrpc.android.XMLRPCException;
import org.xmlrpc.android.XMLRPCFault;

import android.util.Log;

import com.zhu.salesmanagement.common.Actions;

/**
 * XMLRPC 网络请求线程
 */
public class XMLRPCMethod extends Thread{

	public final static int STATUS_SUCCESS = 1;
	public final static int STATUS_FAIL = 0;
	public final static int STATUS_CONNECTERROR = -1;

	private String mMethod;
	private Object[] params;
	private XMLRPCMethodCallback mCallBack;
	private XMLRPCClient mXMLRPCClient = null;
	
	public XMLRPCMethod(String method, XMLRPCMethodCallback callBack, XMLRPCClient client) {
		mMethod = method;
		mCallBack = callBack;
		mXMLRPCClient = client;
	}
	public void call() {
		call(null);
	}
	public void call(Object[] params) {
		this.params = params;
		start();
	}
	@Override
	public void run() {
		try {
			final long t0 = System.currentTimeMillis();
			final Object result = mXMLRPCClient.callEx(mMethod, params);
			final long t1 = System.currentTimeMillis();
			if(Actions.DEBUG){
				Log.e("zhu","XML-RPC call took " + (t1-t0) + "ms");
			}
			mCallBack.callFinished(STATUS_SUCCESS, result);
		} catch (final XMLRPCFault e) {
			if(Actions.DEBUG){
				Log.e("zhu","Fault message: " + e.getFaultString() + "\nFault code: " + e.getFaultCode());
			}
			mCallBack.callFinished(STATUS_FAIL, null);
		} catch (final XMLRPCException e) {
			Throwable couse = e.getCause();
			if (couse instanceof HttpHostConnectException) {
				if(Actions.DEBUG){
					Log.e("zhu","Cannot connect Host");
				}
				mCallBack.callFinished(STATUS_SUCCESS, null);
			} else {
				if(Actions.DEBUG){
					Log.e("zhu","Error " + e.getMessage());
				}
				mCallBack.callFinished(STATUS_FAIL, null);
			}
		}
	}
}
